package com.ljh.mboxvidoserver.system.controller;

import com.ljh.mboxvidoserver.system.entity.LoginUser;
import com.ljh.mboxvidoserver.common.result.entity.Result;
import com.ljh.mboxvidoserver.system.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "system")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "gotoLogin")
    public String gotoLogin(){
        return "system/login";
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public Result login(LoginUser user, HttpSession session){
        Result result = new Result();
        try {
            if(user!=null) {
                user = loginService.login(user);
                result.setStatus("500");
                result.setResult("success");
                result.setMessage("登录成功");
                session.setAttribute("loginUser",user);
            }else{
                result.setStatus("500");
                result.setResult("error");
                result.setMessage("用户名和密码不能为空");
                return result;
            }
        }catch (Exception e){
            result.setStatus("500");
            result.setResult("error");
            result.setMessage(e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping(value = "logout",method = RequestMethod.POST)
    @ResponseBody
    public Result logout(LoginUser user, HttpSession session){
        Result result = new Result();

        LoginUser loginUser = (LoginUser)session.getAttribute("loginUser");
        if(loginUser!=null){
            session.removeAttribute("loginUser");
            result.setMessage("退出系统成功");
            result.setResult("success");
        }else {
            result.setMessage("错误，找不到系统登录用户");
            result.setResult("error");
        }
        result.setStatus("500");
        return result;
    }
}
